package com.compiler.lexico.action;

import java.io.IOException;
import java.io.RandomAccessFile;

import com.compiler.lexico.token.SymbolTable;
import com.compiler.lexico.token.Token;
import com.compiler.syntactic.Parser;

public class InsertId extends AbstractAction {
	private final static String TYPE_ID="Identificador";
	private final static String TYPE_RESERVED="Palabra Reservada";
	
	public InsertId(Token token, SymbolTable symbolTable) {
		super(token,symbolTable);
	}
	
	private void checkRange() {
		if(this.token.getSize() > 16)
			this.token.truncate();
	}

	private int getParserVal() {
		int ret=-20;
		switch (this.token.getData().toUpperCase()) {
		case "PRINT": ret = Parser.PRINT;
			break;
		case "IF": ret = Parser.IF;
			break;
		case "THEN": ret = Parser.THEN;
			break;
		case "UINTEGER": ret = Parser.UINTEGER;
			break;
		case "ELSE": ret = Parser.ELSE;
			break;
		case "FOR": ret = Parser.FOR;
			break;
		case "STEP": ret = Parser.STEP;
			break;
		case "ARRAY": ret = Parser.ARRAY;
			break;
		default:
			break;
		}
		return ret;
	}
	
	@Override
	public void exec(RandomAccessFile raf) throws IOException {
		if(!this.symbolTable.isReservedWord(token)) {
			this.checkRange();
			this.symbolTable.addToken(new Token(token.getData(),TYPE_ID,token.getLine(),Parser.IDENTIFICADOR));
		}
		else
			this.symbolTable.addToken(new Token(token.getData(),TYPE_RESERVED,token.getLine(),this.getParserVal()));
		this.token.clean();
	}

	@Override
	public String toString() {
		return "Insert";
	}

}
